//
//  GetStrWidthAndHeight.m
//  WisdomPartyBuilding
//
//  Created by Can on 2018/4/23.
//  Copyright © 2018年 hwd. All rights reserved.
//

#import "GetStrWidthAndHeight.h"

@implementation GetStrWidthAndHeight

+ (CGFloat)getStringWidthWith:(NSString *)str andHeigth:(CGFloat )h andFont:(UIFont *)font
{
    CGRect rect = [str boundingRectWithSize:CGSizeMake(MAXFLOAT, h) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil] context:nil];
    return rect.size.width;
}

+ (CGFloat)getStringHeightWith:(NSString *)str andWeith:(CGFloat )w andFont:(UIFont *)font
{
    CGRect rect = [str boundingRectWithSize:CGSizeMake(w, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil] context:nil];
    return rect.size.height;
}

+ (CGFloat)getStringHeightWith:(NSString *)str andWeith:(CGFloat )w andFont:(UIFont *)font andLineSpacing:(CGFloat)lineSpacing
{
    if (!str) {
        return 0;
    }
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpacing;
    [attributeString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, str.length)];
    [attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, str.length)];
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    CGRect rect = [attributeString boundingRectWithSize:CGSizeMake(w, MAXFLOAT) options:options context:nil];

    //文本的高度减去字体高度小于等于行间距，判断为当前只有1行
    if ((rect.size.height - font.lineHeight) <= paragraphStyle.lineSpacing) {
        BOOL hasChinese = NO;
        for(int i=0; i< [str length];i++){ int a = [str characterAtIndex:i];
            if( a > 0x4e00 && a < 0x9fff){
                hasChinese = YES;
                break;
            }
        }
        if (hasChinese) {  //如果包含中文
            rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-paragraphStyle.lineSpacing);
        }
    }
    return rect.size.height;
}

//lable高度
+ (CGFloat)lableHeight:(UILabel *)lable{
    lable.numberOfLines = 0;//根据最大行数需求来设置
    lable.lineBreakMode = NSLineBreakByTruncatingTail;
    CGSize maximumLabelSize = CGSizeMake(SCREENW - 54*screenW_6, 9999);//labelsize的最大值
    //关键语句
    CGSize expectSize = [lable sizeThatFits:maximumLabelSize];
    return expectSize.height;
}

@end
